<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert :closable="false" center title="添加商品信息" type="info" show-icon></el-alert>
      <!-- 步骤条区域 -->
      <el-steps align-center :active="+activeIndex">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form label-position="top" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="onTabClick"
        >
          <!-- 基本信息tab -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <!-- 级联选择框 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="cascaderValue"
                :options="goodsCateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数面板 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <!-- 复选框组:商品动态参数 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="element" v-for="element in item.options"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadAction"
              :headers="headers"
              list-type="picture-card"
              :auto-upload="true"
              :on-success="handleSuccess"
              :file-list="fileList"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt>
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <!-- 图片预览对话框 -->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt>
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btn-add" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
// 验证商品价格的检验函数
const checkPrice = (rule, value, cb) => {
  const regPrice = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/
  if (regPrice.test(value) && value > 0) return cb() //通过校验
  return cb('价格必须是大于0的数字')
}
// 校验商品的重量
const checkWeight = (rule, value, cb) => {
  const regWeight = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/
  if (regWeight.test(value) && value > 0) return cb() //通过校验
  return cb('重量必须是大于0的数字')
}
// 校验商品数量
const checkNumber = (rule, value, cb) => {
  const regNumber = /^\d{1,}$/
  if (regNumber.test(value) && value > 0) return cb() //通过校验
  return cb('数量必须是大于0的数字')
}
export default {
  data() {
    return {
      // 步骤条高亮
      activeIndex: '0',
      //   表单对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: '',
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      //   级联选择框通过v-model绑定的数据
      cascaderValue: [],
      //   表单验证规则
      addFormRules: {
        //   商品名称验证规则
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 商品价格验证规则
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkPrice, trigger: 'blur' }
        ],
        // 商品重量验证规则
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: checkWeight, trigger: 'blur' }
        ],
        // 商品数量验证规则
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        // 商品分类验证规则
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //   商品分类数据
      goodsCateList: [],
      //   级联选择框配置项
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数数据
      manyData: [],
      // 静态属性数据
      onlyData:[],
      // 图片预览三个data
       dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        // 上传组件要请求的接口地址
        uploadAction:'http://127.0.0.1:8888/api/private/v1/upload',
        headers:{
          Authorization:window.sessionStorage.getItem('token')
        },
        fileList:[]
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //   获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类数据失败!')
      this.goodsCateList = res.data
    },
    // 处理级联选择框配置项改变
    handleChange() {
      //   console.log(this.cascaderValue);
      this.manyData=[]
      this.onlyData=[]
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.addForm.goods_cat = ''
        return
      }
      //   把级联选择器分类的id转化为字符串存到表单中
      this.addForm.goods_cat = this.cascaderValue.join(',')
      // console.log(this.addForm)
    },
    // 切换标签之前的函数,用来阻止切换的
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == '0' && this.cascaderValue.length !== 3) {
        this.$message.error('请选择商品分类后切换!')
        return false
      }
    },
    // 点击tab
    async onTabClick() {
      if (this.activeIndex === '1' && this.cateId!==null) {
        if(this.manyData.length!==0) return 
        // 发起网络请求,获取动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取动态参数失败')
          console.log(res.data);
          // 通过循环的方式把数组中item的attr_vals属性转化成数组
          res.data.forEach(item=>{
            const valStr=item.attr_vals
            item.attr_vals=item.attr_vals.length==0?[]:item.attr_vals.split(',')
            // 配置一个options属性,防止复选框不被选中从页面消失
            item.options=item.attr_vals.length==0?[]:valStr.split(',')
          })
        this.manyData = res.data
      }else if(this.activeIndex === '2' && this.cateId!==null) {
        if(this.onlyData.length!==0) return 
             // 发起网络请求,获取动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取静态属性失败')
          // 通过循环的方式把数组中item的attr_vals属性转化成数组
         
        this.onlyData = res.data
      }
    },
    // 上传图片两个事件
     handleRemove(file) {
        console.log(file);
       this.addForm.pics= this.addForm.pics.filter(x =>x.pic!==file.response.data.tmp_path)
      //  把要删除的图片,从fileList中移出,让其在页面上消失
      this.fileList= this.fileList.filter(x=>x.uid!==file.uid)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 监听上传图片
      handleSuccess(res,file,fileList) {
        // console.log(res);
        const picInfo={pic:res.data.tmp_path}
        this.addForm.pics.push(picInfo)
        // console.log( this.addForm.pics);
        this.fileList=fileList
      },
      // 添加商品
      addGoods() {
        // console.log(this.addForm);
        this.$refs.addFormRef.validate(async valid=>{
          if(!valid) return this.$message.error('请填写必要表单项')
          // 处理动态参数
          this.manyData.forEach(item=>{
            // console.log(item);
            const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(',')}
            this.addForm.attrs.push(newInfo)

          })
          // 处理静态属性
          this.onlyData.forEach(item=>{
             const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
            this.addForm.attrs.push(newInfo)
          })
        // 执行添加商品的操作
        console.log(this.addForm);
        const {data:res}=await this.$http.post('goods',this.addForm)
        if(res.meta.status!==201) return this.$message.error(res.meta.msg)
        this.$message.success('添加商品成功!')
        this.$router.push('/goods')
        })
      
        
      }
  },
  computed: {
    cateId() {
      if (this.cascaderValue.length == 3) {
        return this.cascaderValue[2]
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
/deep/ .el-step__title {
  font-size: 12px;
}
/deep/ .el-step__icon {
  font-size: 12px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.btn-add {
  margin-top: 15px;
}
</style>

